package com.taihua_tech.basic.util;

import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;

public class CryptionUtil {
	private static final String DES_ALGORITHM = "DES/CBC/PKCS5Padding";

	public static String encryption(String plainData, String secretKey) {
		String result = null;
		try {
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			IvParameterSpec ivParameterSpec = new IvParameterSpec(secretKey.getBytes("UTF-8"));
			cipher.init(1, generateKey(secretKey), ivParameterSpec);
			byte[] buf = cipher.doFinal(plainData.getBytes());
			result = Base64.encodeBase64String(buf);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String decryption(String secretData, String secretKey) {
		String result = null;
		try {
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			IvParameterSpec ivParameterSpec = new IvParameterSpec(secretKey.getBytes("UTF-8"));
			cipher.init(2, generateKey(secretKey), ivParameterSpec);
			byte[] buf = cipher.doFinal(Base64.decodeBase64(secretData));
			result = new String(buf, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	private static SecretKey generateKey(String secretKey) {
		try {
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			DESKeySpec keySpec = new DESKeySpec(secretKey.getBytes());
			keyFactory.generateSecret(keySpec);
			return keyFactory.generateSecret(keySpec);
		} catch (Exception e) {
			e.printStackTrace();
		}
		throw new RuntimeException("generate secretKey fail !!");
	}

	private static String byteArray2HexStingr(byte[] bs) {
		StringBuffer sb = new StringBuffer();
		byte[] arrayOfByte = bs;
		int j = bs.length;
		for (int i = 0; i < j; i++) {
			byte b = arrayOfByte[i];
			sb.append(byte2HexString(b));
		}
		return sb.toString();
	}

	private static String byte2HexString(byte b) {
		String hexStr = null;
		int n = b;
		if (n < 0) {
			n = b & 0xFF;
		}
		hexStr = Integer.toHexString(n / 16) + Integer.toHexString(n % 16);
		return hexStr.toUpperCase();
	}

	public static String md5Hex(String origString) {
		String origMD5 = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] result = md5.digest(origString.getBytes("UTF-8"));
			origMD5 = byteArray2HexStingr(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return origMD5;
	}

	public static void main(String[] args) throws Exception {
		// 加密
		String pwd = CryptionUtil.encryption("DEMOTEST", "12345678");
		System.out.println(pwd);
		// 解密
		System.out.println(CryptionUtil.decryption(pwd, "12345678"));
		// md5
		System.out.println(CryptionUtil.md5Hex( "admin"));
	}

}